package de.grosjohann.android.feuerwehr.domain;

import java.io.Serializable;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import de.grosjohann.android.feuerwehr.type.WeatherWarningType;
import de.grosjohann.android.feuerwehr.util.StringUtil;

public class WeatherWarning
  extends AbstractWarning<WeatherWarningType>
  implements Serializable {

  private final String msg;
  private final String detail;
  private final String end;

  public WeatherWarning(JSONObject obj) throws JSONException {
    super(WeatherWarningType.valueOf(obj.getInt("level")));
    msg = obj.getString("msg");
    end = obj.has("end") ? obj.getString("end") : null;
    detail = obj.has("detail") ? obj.getString("detail") : StringUtil.EMPTY;
  }

  public String getMessage() {
    return msg;
  }

  public String getDetail() {
    return detail;
  }

  public String getEnd() {
    return end;
  }

  @Override
  public String toString() {
    return getLevel().name() + ": " + msg;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((end == null) ? 0 : end.hashCode());
    result = prime * result + ((getLevel() == null) ? 0 : getLevel().hashCode());
    result = prime * result + ((msg == null) ? 0 : msg.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    WeatherWarning other = (WeatherWarning) obj;
    if (end == null) {
      if (other.end != null)
        return false;
    } else if (!end.equals(other.end))
      return false;
    if (getLevel() != other.getLevel())
      return false;
    if (msg == null) {
      if (other.msg != null)
        return false;
    } else if (!msg.equals(other.msg))
      return false;
    return true;
  }

  public static WeatherWarning getHighestWarning(List<WeatherWarning> list) {
    WeatherWarning highestWarning = null;
    for (WeatherWarning warning : list) {
      if (highestWarning == null || warning.getLevel().getLevel() > highestWarning.getLevel().getLevel()) {
        highestWarning = warning;
      }
    }
    return highestWarning;
  }

}
